package app.com.rtsplibrary.rtsp;



import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;

import app.com.rtsplibrary.data.VDataUtil;
import app.com.rtsplibrary.data.H264Data;

/**SurfaceCallback
 * Created by user111 on 2018/3/14.
 */

public class H264InputStream extends InputStream {

    private final static String TAG = "H264InputStream";
    private long ts = 0;
    private ByteBuffer mBuffer = null;
    private H264Data data = null;
    private VDataUtil VDataUtil;
    private boolean is_close = false;

    public H264InputStream(){
        Log.d(TAG, "H264InputStream OPEN");
        VDataUtil = new VDataUtil();
        is_close = false;
    }




    @Override
    public int read(byte[] buffer, int offset, int length) throws IOException {
        int min = 0;

        if(is_close){
            return -1;
        }

        if(mBuffer == null){
            try {
                data = VDataUtil.getH264Queue().poll(1000, TimeUnit.MICROSECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(data == null) {
                return 0;
            }
            ts = data.ts;
            mBuffer = ByteBuffer.wrap(data.data);
            mBuffer.position(0);
        }
        min = length < data.data.length - mBuffer.position() ? length : data.data.length - mBuffer.position();
        mBuffer.get(buffer, offset, min);
        if (mBuffer.position()>=data.data.length) {
            mBuffer = null;
        }
        return min;
    }


    @Override
    public int read() throws IOException {
        return 0;
    }

    public int available() {
        if (mBuffer != null)
            return data.data.length - mBuffer.position();
        else
            return 0;
    }

    @Override
    public void close() throws IOException {
        super.close();
        is_close = true;
        if(VDataUtil != null){
            VDataUtil.close();
        }
        Log.d(TAG, "H264InputStream CLOSE");
    }

    public long getLastts(){
        return ts;
    }
}
